# -*- coding: utf-8 -*-
import sqlite3
import datetime
import time
import sys, os

DEBUG = False
DB_FILENAME = "AddressBook.sqlitedb"
IPHONE = (sys.platform == "darwin")

if IPHONE:
    ALERT = "/bin/alert -t 'Recuerda:' -b '%s'"
    DB_PATH = "/var/mobile/Library/AddressBook"
else:
    ALERT = "/usr/bin/zenity --info --text='%s'"
    DB_PATH = "/home/nauj27/Proyectos/BirthdayReminder"

def iphone2unixtime(timestamp):
    return timestamp + 978307200

def unixtime2iphone(timestamp):
    return timestamp - 978307200

def parseDatetime(myDatetime):
    dateFormat = "%Y-%m-%d"
    return int(time.mktime(time.strptime(myDatetime, dateFormat)))


class Contact(object):
    def __init__(self, contactInfo):
        self.contactInfo = contactInfo
        
        self.first = (contactInfo[0] or "")
        self.middle = (contactInfo[1] or "")
        self.last = (contactInfo[2] or "")
        self.birthday = contactInfo[3]
        
    def isBirthday(self):
        if self.birthday:
            if DEBUG:
                today = datetime.date(2008, 2, 17)
            else:
                today = datetime.date.today()
            birthday = datetime.datetime.fromtimestamp(iphone2unixtime(float(self.birthday)))
            if ((today.month == birthday.month) and (today.day == birthday.day)):
                return True
            else:
                return False
        else:
            return False
        

class AddressBook(object):
    def __init__(self):
        self.database = sqlite3.connect("%s/%s" % (DB_PATH, DB_FILENAME,))
        
    def peopleBirthday(self):
        ''' Return array with people with today birthday '''
        contactBirthdayList = []
        cursor = self.database.execute("SELECT First, Middle, Last, Birthday FROM ABPerson;")
        for row in cursor.fetchall():
            contact = Contact(row)
            if contact.isBirthday():
                contactBirthdayList.append(contact)
                
        return contactBirthdayList
        

if __name__ == "__main__":
    addressBook = AddressBook()
    people = addressBook.peopleBirthday()
    names = [(u"%s %s %s" % (c.first, c.middle, c.last,)) for c in people]
    if len(names) <> 0:
        if IPHONE:
            os.popen("/bin/playaudio /Library/Ringtones/Boing.m4r")
        os.popen(ALERT % (u"Hoy es el cumple de %s" % (",".join(names),),))
    